<template>
  <div class="admin-system-config">
    <!-- 头部工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新增配置
      </el-button>
      <el-button type="success" @click="handleRefreshCache">
        <el-icon><Refresh /></el-icon>
        刷新缓存
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="配置分组">
          <el-select v-model="searchForm.configGroup" placeholder="选择配置分组" clearable>
            <el-option 
              v-for="group in configGroups"
              :key="group"
              :label="group"
              :value="group"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置键">
          <el-input 
            v-model="searchForm.configKey" 
            placeholder="请输入配置键"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadConfigs">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading"
    >
      <el-table-column prop="configKey" label="配置键" width="200" />
      <el-table-column prop="configValue" label="配置值" min-width="200">
        <template #default="scope">
          <span class="config-value">{{ scope.row.configValue || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="200" />
      <el-table-column prop="configGroup" label="分组" width="120" />
      <el-table-column prop="editable" label="可编辑" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.editable === 1 ? 'success' : 'warning'">
            {{ scope.row.editable === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button 
            type="text" 
            class="danger" 
            @click="handleDelete(scope.row)"
            :disabled="scope.row.editable === 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadConfigs"
        @current-change="loadConfigs"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="配置键" prop="configKey">
          <el-input 
            v-model="formData.configKey" 
            placeholder="请输入配置键"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <el-input 
            v-model="formData.configValue" 
            type="textarea"
            :rows="3"
            placeholder="请输入配置值"
          />
        </el-form-item>
        <el-form-item label="配置描述">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="2"
            placeholder="请输入配置描述"
          />
        </el-form-item>
        <el-form-item label="配置分组">
          <el-input v-model="formData.configGroup" placeholder="请输入配置分组" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="可编辑">
          <el-switch 
            v-model="formData.editable"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog 
      title="配置详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="配置键">{{ currentConfig.configKey }}</el-descriptions-item>
        <el-descriptions-item label="配置值">
          <pre class="config-value-detail">{{ currentConfig.configValue || '-' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="配置描述">{{ currentConfig.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="配置分组">{{ currentConfig.configGroup || '-' }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ currentConfig.sortOrder || 0 }}</el-descriptions-item>
        <el-descriptions-item label="可编辑">
          <el-tag :type="currentConfig.editable === 1 ? 'success' : 'warning'">
            {{ currentConfig.editable === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentConfig.status === 1 ? 'success' : 'danger'">
            {{ currentConfig.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentConfig.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(currentConfig.updatedAt) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { 
  getSystemConfigPage, 
  createSystemConfig, 
  updateSystemConfig, 
  deleteSystemConfig,
  getSystemConfigGroups,
  refreshSystemConfigCache
} from '@/api/systemConfig'

export default {
  name: 'AdminSystemConfig',
  components: {
    Plus,
    Refresh
  },
  setup() {
    const loading = ref(false)
    const tableData = ref([])
    const configGroups = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      configGroup: '',
      configKey: ''
    })

    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 对话框
    const dialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)
    const currentConfig = ref({})
    
    // 表单
    const formRef = ref(null)
    const formData = reactive({
      configKey: '',
      configValue: '',
      description: '',
      configGroup: '',
      sortOrder: 0,
      editable: 1,
      status: 1
    })

    const formRules = {
      configKey: [
        { required: true, message: '请输入配置键', trigger: 'blur' },
        { pattern: /^[a-zA-Z][a-zA-Z0-9._-]*$/, message: '配置键格式不正确', trigger: 'blur' }
      ]
    }

    // 加载配置分组
    const loadConfigGroups = async () => {
      try {
        const response = await getSystemConfigGroups()
        configGroups.value = response.data || []
      } catch (error) {
        console.error('加载配置分组失败:', error)
      }
    }

    // 加载配置列表
    const loadConfigs = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          size: pagination.size,
          ...searchForm
        }
        
        const response = await getSystemConfigPage(params)
        const data = response.data
        
        tableData.value = data.records || []
        pagination.total = data.total || 0
      } catch (error) {
        console.error('加载配置列表失败:', error)
        ElMessage.error('加载配置列表失败')
      } finally {
        loading.value = false
      }
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        configGroup: '',
        configKey: ''
      })
      pagination.page = 1
      loadConfigs()
    }

    // 显示新增对话框
    const showCreateDialog = () => {
      dialogTitle.value = '新增配置'
      isEdit.value = false
      dialogVisible.value = true
      resetForm()
    }

    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑配置'
      isEdit.value = true
      dialogVisible.value = true
      Object.assign(formData, row)
    }

    // 查看详情
    const handleView = (row) => {
      currentConfig.value = { ...row }
      detailDialogVisible.value = true
    }

    // 删除
    const handleDelete = async (row) => {
      if (row.editable === 0) {
        ElMessage.warning('该配置不可编辑，无法删除')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要删除配置"${row.configKey}"吗？`,
          '确认删除',
          { type: 'warning' }
        )
        
        await deleteSystemConfig(row.id)
        ElMessage.success('删除成功')
        loadConfigs()
        loadConfigGroups()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 刷新缓存
    const handleRefreshCache = async () => {
      try {
        await refreshSystemConfigCache()
        ElMessage.success('缓存刷新成功')
      } catch (error) {
        console.error('刷新缓存失败:', error)
        ElMessage.error('刷新缓存失败')
      }
    }

    // 保存
    const handleSave = async () => {
      try {
        await formRef.value.validate()
        
        if (isEdit.value) {
          await updateSystemConfig(formData.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createSystemConfig(formData)
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadConfigs()
        loadConfigGroups()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(formData, {
        configKey: '',
        configValue: '',
        description: '',
        configGroup: '',
        sortOrder: 0,
        editable: 1,
        status: 1
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    }

    onMounted(() => {
      loadConfigGroups()
      loadConfigs()
    })

    return {
      loading,
      tableData,
      configGroups,
      searchForm,
      pagination,
      dialogVisible,
      detailDialogVisible,
      dialogTitle,
      isEdit,
      currentConfig,
      formRef,
      formData,
      formRules,
      loadConfigs,
      resetSearch,
      showCreateDialog,
      handleEdit,
      handleView,
      handleDelete,
      handleRefreshCache,
      handleSave,
      resetForm,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.admin-system-config {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.search-form {
  background: #f5f5f5;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.danger {
  color: #f56c6c;
}

.config-value {
  word-break: break-all;
  max-width: 200px;
  display: inline-block;
}

.config-value-detail {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', monospace;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>